package com.tools.scanner.ui.dialog

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Base64
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.tools.scanner.R
import com.tools.scanner.bean.SharePlatformInfo
import com.tools.scanner.databinding.DialogShareBinding
import com.tools.scanner.databinding.RecyclerShareItemBinding
import com.tools.scanner.utils.AppUtil
import com.tools.scanner.viewmodel.DataViewModel

class ShareDialog : BottomSheetDialogFragment() {

    private lateinit var mBinding: DialogShareBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = DialogShareBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    private val mPlatformPkgNameList = mutableListOf(
        "com.facebook.katana",
        "com.facebook.orca",
        "com.instagram.android",
        "com.whatsapp",
        "org.telegram.messenger"
    )
    private val mSharePlatformList = mutableListOf<SharePlatformInfo>()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.ivBack.setOnClickListener {
            dismissAllowingStateLoss()
        }

        val activity = requireActivity()
        activity.packageManager.let {
            addKnownSharePlatform(it)
            addUnknownSharePlatform(it)
        }

        mBinding.recyclerView.layoutManager = GridLayoutManager(activity, 4)
        mBinding.recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {

            private val margin = activity.resources.getDimension(R.dimen.dp_10).toInt()

            override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
                super.getItemOffsets(outRect, itemPosition, parent)

                if (itemPosition < 4) {
                    outRect.top = margin
                }

                outRect.bottom = margin
            }
        })
        mBinding.recyclerView.adapter = ShareAdapter(mSharePlatformList) {
            AppUtil.shareApp(it)
        }
    }

    private fun addKnownSharePlatform(packageManager: PackageManager) {
        mPlatformPkgNameList.forEach { pkgName ->
            try {
                val packageInfo = packageManager.getPackageInfo(pkgName, 0)
                if (packageInfo != null) {
                    val applicationInfo = packageInfo.applicationInfo
                    val label = applicationInfo.loadLabel(packageManager).toString()
                    val loadIcon = applicationInfo.loadIcon(packageManager)
                    mSharePlatformList.add(SharePlatformInfo(pkgName, loadIcon, label))
                }
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }
        }
    }

    private fun addUnknownSharePlatform(packageManager: PackageManager) {
        val shareInfo = DataViewModel.getShareInfo()

        val intent = Intent("android.intent.action.SEND")
        intent.setType("text/plain")
        intent.putExtra("android.intent.extra.TEXT", Base64.decode(shareInfo.title, Base64.DEFAULT))
        intent.putExtra(
            "android.intent.extra.SUBJECT",
            Base64.decode(shareInfo.content, Base64.DEFAULT)
        )

        packageManager.queryIntentActivities(intent, 0).forEach { resolveInfo ->
            val pkgName = resolveInfo.activityInfo.packageName
            if (!mPlatformPkgNameList.contains(pkgName)) {
                val label = resolveInfo.loadLabel(packageManager).toString()
                val loadIcon = resolveInfo.loadIcon(packageManager)
                mSharePlatformList.add(SharePlatformInfo(pkgName, loadIcon, label))
            }
        }
    }
}

class ShareAdapter(
    private val shareList: List<SharePlatformInfo>,
    private val callback: (SharePlatformInfo) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding = RecyclerShareItemBinding.inflate(layoutInflater, parent, false)
        return ShareViewHolder(binding, callback)
    }

    override fun getItemCount(): Int {
        return shareList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is ShareViewHolder) {
            holder.refresh(shareList[position])
        }
    }

    private class ShareViewHolder(
        private val mBinding: RecyclerShareItemBinding,
        private val callback: (SharePlatformInfo) -> Unit
    ) : RecyclerView.ViewHolder(mBinding.root) {

        init {
            mBinding.root.setOnClickListener {
                val tag = it.tag
                if (tag is SharePlatformInfo) {
                    callback(tag)
                }
            }
        }

        fun refresh(item: SharePlatformInfo) {
            mBinding.root.tag = item
            mBinding.icon.setImageDrawable(item.icon)
            mBinding.tvName.text = item.label
        }
    }

}







